package com.zbkj.crmeb.merchant.api.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.google.common.collect.Lists;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.utils.ProductConvertUtil;
import com.zbkj.crmeb.chant.model.ChannelActivity;
import com.zbkj.crmeb.chant.model.ChannelMemberLevel;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelPicking;
import com.zbkj.crmeb.chant.request.ActivityDetailsRequest;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ChannelActivityService;
import com.zbkj.crmeb.chant.service.ChannelPickingService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.merchant.admin.service.StoreProductStockService;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.user.model.UserMemberRecord;
import com.zbkj.crmeb.user.service.UserMemberRecordService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageHelper;
import com.utils.PriceUtil;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.express.service.FirstLogisticsCostService;
import com.zbkj.crmeb.front.request.CartResetRequest;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.merchant.api.service.MerStoreCartService;
import com.zbkj.crmeb.store.dao.StoreCartDao;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserLevelService;
import com.zbkj.crmeb.user.service.UserService;

/**
* @author Mr.Zhang
* @description StoreCartServiceImpl 接口实现
* @date 2020-05-28 edit by stivepeim 2020-7-4
*/
@Slf4j
@Service
public class MerStoreCartServiceImpl extends ServiceImpl<StoreCartDao, StoreCart> implements MerStoreCartService {
    @Resource
    private StoreCartDao dao;
    @Autowired
    private MerStoreProductService storeProductService;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private UserLevelService userLevelService;
    @Autowired
    private MarkupRateService markupRateService;
    @Autowired
    FirstLogisticsCostService firstLogisticsCostService;
    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    private StoreProductPickingService storeProductPickingService;
    @Autowired
    private StoreProductStockService storeProductStockService;
    @Autowired
    private ChannelPickingService channelPickingService;
    @Autowired
    private ChannelActivityService channelActivityService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ChannelGroupBookingService channelGroupBookingService;
    @Autowired
    private StoreProductGroupActivityService storeProductGroupActivityService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private UserMemberRecordService userMemberRecordService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private StoreSaleAnalysisService storeSaleAnalysisService;

    /**
    * 列表
    * @param pageParamRequest 分页类参数
    * @author Mr.Zhang edite by stivepeim 2020-7-4
    * @since 2020-05-28
    * @return List<StoreCart>
    */
    @Override
    public List<StoreCartResponse> getList(PageParamRequest pageParamRequest, StoreCart cart, boolean isValid, Integer merId, Integer[] areaType) {
        // TODO
    	// 分页前先请求库存是否为0 更新购物车状态(后期可优化掉)
        if(isValid) {
            LambdaQueryWrapper<StoreCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StoreCart::getUid, cart.getUid());
            queryWrapper.eq(StoreCart::getPickingId,cart.getPickingId());
            List<StoreCart> carts = dao.selectList(queryWrapper);

            List<Integer> enableCategoryMatchIds = categoryMatchService.getCategoryMatchIds(merId);
            List<Integer> ids = carts.stream().map(StoreCart::getProductId).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(ids)) {
            	return new ArrayList<>();
            }
            // 商品数据
            List<StoreProduct> products = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery()
            		.in(StoreProduct :: getId, ids)
            		);
            Map<Integer, StoreProduct> productMap = products.stream().collect(Collectors.toMap(StoreProduct::getId, Function.identity(), (key1, key2) -> key2));
            // 商户自定义商品数据
            List<StoreProductMer> storeProductMers = storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery()
            		.in(StoreProductMer :: getProductId, ids)
            		);
            Map<Integer, StoreProductMer> storeProductMerMap = storeProductMers.stream().collect(Collectors.toMap(StoreProductMer::getProductId, Function.identity(), (key1, key2) -> key2));
            carts.forEach(c -> {
                StoreProduct p = productMap.get(c.getProductId());
                if(null != p){
                    StoreProductMer spm = storeProductMerMap.get(p.getId());
                    // 商户自定义下架状态
                    boolean isMerShow = true;
                    if(null != spm && "1".equals(spm.getIsNotShow())) {
                    	isMerShow = false;
                    }
                    //分类未启用时设置商品状态为失效
                    boolean enableCategoryBool = !enableCategoryMatchIds.contains(p.getCateId());
                    if(c.getStatus()){
                        if(p.getStock() < 1 || !p.getIsShow() || !isMerShow || enableCategoryBool){
                            c.setStatus(false);
                            dao.updateById(c);
                        }
                    }else {
                        if(p.getStock() > 0 && p.getIsShow() && isMerShow && !enableCategoryBool){
                            c.setStatus(true);
                            dao.updateById(c);
                        }
                    }
                }else{
                    c.setStatus(false);
                    dao.updateById(c);
                }
            });
        }

        /**** 查询需要返回的数据 ****/
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带 StoreCart 类的多条件查询
        LambdaQueryWrapper<StoreCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreCart::getUid, cart.getUid());
        if(cart.getIsNew()!=null){
            lambdaQueryWrapper.eq(StoreCart::getIsNew, cart.getIsNew());
        }
        if(cart.getPickingId() != null){
            lambdaQueryWrapper.eq(StoreCart::getPickingId, cart.getPickingId());
        }
        lambdaQueryWrapper.eq(StoreCart::getStatus, isValid);
        lambdaQueryWrapper.orderByDesc(StoreCart::getCreateTime);
        List<StoreCart> storeCarts = dao.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(storeCarts)){
            return new ArrayList<>();
        }
        List<Integer> ids = storeCarts.stream().map(StoreCart::getProductId).collect(Collectors.toList());
        // 查询商品pojo对象
        List<StoreProductResponse> storeProductResponses = storeProductService.getMerchnatList(ids, merId,true);
        Map<Integer, StoreProductResponse> storeProductResponseMap = storeProductResponses.stream().collect(Collectors.toMap(StoreProductResponse::getId, Function.identity(), (key1, key2) -> key2));
        //查询商品活动,预热时间重叠时取活动开始时间最近的
        List<String> skuIds = storeCarts.stream().map(StoreCart::getProductAttrUnique).collect(Collectors.toList());
        ActivityDetailsRequest detailsRequest = new ActivityDetailsRequest();
        detailsRequest.setMerId(merId);
        detailsRequest.setEventTimeType(2);
        detailsRequest.setCurrentTime(new Date());
        detailsRequest.setProductIdList(ids);
        detailsRequest.setSourceSkuIdList(skuIds);
        List<ChannelActivity> activityList = channelActivityService.getActivityBySkuId(detailsRequest);
        Map<String,ChannelActivity> activityMap = activityList.stream().collect(Collectors.toMap(ChannelActivity::getSourceSkuId,channelActivity -> channelActivity, (ca1,ca2) -> {
            if (ca1.getStartTime().before(ca2.getStartTime())){
                return ca1;
            }else {
                return ca2;
            }
        }));

        List<StoreCartResponse> response = new ArrayList<>();
        List<StoreCartResponse> invalidProduct = new ArrayList<>();
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);

        User user = userService.getById(cart.getUid());
        // 无订单用户
        int orderCount = storeOrderService.
                count(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getUid, cart.getUid()));
        //查询用户是否已开启会员
        int count  = userMemberRecordService.count(Wrappers.lambdaQuery(UserMemberRecord.class)
                .eq(UserMemberRecord::getPaid,true)
                .gt(UserMemberRecord::getExpirationTime,new Date())
                .eq(UserMemberRecord::getUid, cart.getUid()));
        for (StoreCart storeCart : storeCarts) {
            // 属性不存在证明失效
            StoreCartResponse storeCartResponse = new StoreCartResponse();
            BeanUtils.copyProperties(storeCart, storeCartResponse);
            StoreProductResponse product = storeProductResponseMap.get(storeCart.getProductId());
            if (null == product){
                continue;
            }
            StoreProductCartProductInfoResponse p = new StoreProductCartProductInfoResponse();
            BeanUtils.copyProperties(product, p);
            storeCartResponse.setProductInfo(p);
            storeCartResponse.setAttrStatus(false);

            List<StoreProductAttrValueResponse> attrValueList = product.getAttrValue();
            if(null != storeCart.getProductAttrUnique()){
                attrValueList = attrValueList.stream().filter(e -> Objects.equals(e.getSourceSkuId(), storeCart.getProductAttrUnique())).collect(Collectors.toList());
            }

            if(CollectionUtils.isNotEmpty(attrValueList)){
                for (StoreProductAttrValueResponse productAttrValueResponse : attrValueList) {
                    StoreProductAttrValue productAttrValue = new StoreProductAttrValue();
                    BeanUtils.copyProperties(productAttrValueResponse, productAttrValue);
                    // 主图覆盖
                    if(StringUtils.isBlank(productAttrValue.getImage())){
                        productAttrValue.setImage(p.getImage());
                    }
                    // 商品是否失效
                    if(StringUtils.isBlank(productAttrValue.getSuk())){
                        p.setAttrInfo(productAttrValue.setSuk("已失效"));
                    }else{
                        p.setAttrInfo(productAttrValue);
                    }
                    storeCartResponse.setAttrStatus(productAttrValue.getStock() > 0);
                    storeCartResponse.setTaxAndSecondPrice(productAttrValue.getTaxAndSecondPrice());
                    storeCartResponse.setTruePrice(productAttrValue.getPrice());
//                    storeCartResponse.setVipTruePrice(setVipPrice(productAttrValue.getPrice(), userService.getUserIdException(),false));
                    storeCartResponse.setTrueStock(productAttrValue.getStock());
                    storeCartResponse.setCostPrice(product.getCost());
                }
            }else {
                StoreProductAttrValue productAttrValue = new StoreProductAttrValue();
                productAttrValue.setImage(p.getImage());
                p.setAttrInfo(productAttrValue.setSuk("已失效"));
            }
            //设置活动价格
            if (Objects.nonNull(activityMap.get(storeCart.getProductAttrUnique()))){
                ChannelActivity channelActivity = activityMap.get(storeCart.getProductAttrUnique());
                channelActivity.setCanBuy(1);
                if (Objects.equals(channelActivity.getCrowd(),1)){
                    channelActivity.setCanBuy(2);
                }
                if (Objects.equals(channelActivity.getCrowd(),2) && orderCount == 0){
                    channelActivity.setCanBuy(2);
                }
                if (Objects.equals(channelActivity.getCrowd(),3) && user.getCreateTime().getTime() > channelActivity.getCreateTime().getTime()){
                    channelActivity.setCanBuy(2);
                }
                if (Objects.equals(channelActivity.getCrowd(),4) && count > 0){
                    channelActivity.setCanBuy(2);
                }
                if (Objects.equals(channelActivity.getCanBuy(),2) && channelActivity.getLimitTotal() > 0){
                    //限量处理
                    int orderNum = storeOrderInfoService.count(Wrappers.<StoreOrderInfo>lambdaQuery()
                            .eq(StoreOrderInfo::getActivityId, channelActivity.getId())
                            .gt(StoreOrderInfo::getCreateTime, channelActivity.getStartTime())
                            .inSql(StoreOrderInfo::getOrderId, "SELECT id FROM eb_store_order where mer_id = " + channelMerchant.getId() + " and uid = "+ user.getUid()));

                    if (orderNum >= channelActivity.getLimitTotal()){
                        channelActivity.setCanBuy(channelActivity.getLimited());
                    }
                }
                storeCartResponse.setChannelActivity(channelActivity);
                if (Objects.isNull(channelActivity.getSpikePrice()) || channelActivity.getSpikePrice().compareTo(BigDecimal.ZERO) <= 0){
                    channelActivity.setSpikePrice(channelMerchant.getAppletType() == 1 ? storeCartResponse.getTruePrice().add(storeCartResponse.getTaxAndSecondPrice()) : storeCartResponse.getTruePrice());
                    //storeCartResponse.setTruePrice(channelMerchant.getAppletType() == 1 ? channelActivity.getSpikePrice().subtract(storeCartResponse.getTaxAndSecondPrice()) : channelActivity.getSpikePrice());
                }
            }
            if(!storeCartResponse.getAttrStatus()){
                invalidProduct.add(storeCartResponse);
            }else{
                response.add(storeCartResponse);
            }
        }
        response.addAll(invalidProduct);
        if(CollectionUtils.isNotEmpty(response) && ArrayUtils.isNotEmpty(areaType)){
            // 取出所有商品, 用areaType过滤
            List<Integer> areaList = Lists.newArrayList(areaType);
            // 大陆的
            if(areaList.get(0) == 1) {
                response = response.stream().filter(e->areaList.contains(e.getProductInfo().getTempId())).collect(Collectors.toList());
                // 其他地区
            } else {
                response = response.stream().filter(e->1 != e.getProductInfo().getTempId()).collect(Collectors.toList());
            }
        }
        return response;
    }

    /**
     * 根据用户id和购物车id查询
     * @param userId 用户id
     * @param cartIds 购物车id集合
     * @return 购物车列表
     */
    @Override
    public List<StoreCartResponse> getListByUserIdAndCartIds(Integer userId, List<Integer> cartIds,ChannelMerchant channelMerchant, String groupId) {
        LambdaQueryWrapper<StoreCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(StoreCart::getId,cartIds);
        lambdaQueryWrapper.eq(StoreCart::getUid, userId);
        lambdaQueryWrapper.orderByDesc(StoreCart::getCreateTime);
        List<StoreCart> storeCarts = dao.selectList(lambdaQueryWrapper);
        List<StoreCartResponse> response = new ArrayList<>();

        List<Integer> list = storeCarts.stream().map(StoreCart::getPickingId).distinct().collect(Collectors.toList());
        if(list.size() != 1){
            throw new CrmebException("订单异常");
        }
        Integer pickingId = list.get(0);
        //查询批采商品
        Map<String, StoreProductPicking> pickingMap = new HashMap<>();
        ChannelPicking channelPicking = new ChannelPicking();
        if(pickingId > 0){
            channelPicking = channelPickingService.getById(pickingId);
            if(channelPicking == null || channelPicking.getIsDel() == 1){
                throw new CrmebException("该批采单不存在");
            }
            if(channelPicking.getStatementTime().before(new Date())){
                throw new CrmebException("该批采单已过期");
            }
            List<String> valueIdList = storeCarts.stream().map(StoreCart::getProductAttrUnique).distinct().collect(Collectors.toList());
            List<StoreProductPicking> productPickingList = storeProductPickingService.list(Wrappers.<StoreProductPicking>lambdaQuery().eq(StoreProductPicking::getPickingId, pickingId)
                    .in(StoreProductPicking::getSkuId, valueIdList));
            pickingMap = productPickingList.stream().collect(Collectors.toMap(StoreProductPicking::getSkuId, e -> e));
        }
        List<Integer> productIdList = storeCarts.stream().map(StoreCart::getProductId).distinct().collect(Collectors.toList());
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, productIdList));
        //图片
        productConvertUtil.convertProductImage(productList);
        Map<Integer, StoreProduct> productMap = productList.stream().collect(Collectors.toMap(StoreProduct::getId, e -> e));
        ChannelMemberLevel userMemberLevel = userService.getUserMemberLevel(userService.getInfo());
        for (StoreCart storeCart : storeCarts) {
            //List<StoreProductAttrValue> productAttrValues = storeProductAttrValueService.getListByProductIdAndAttrId(storeCart.getProductId(),storeCart.getProductAttrUnique());
            // TODO DIDIOK PRICE -8
            List<StoreProductAttrValue> productAttrValues = storeProductAttrValueService.getListByProductIdAndSkuId(storeCart.getProductId(),storeCart.getProductAttrUnique());
            // TODO calcStockAndPrice
//            storeProductStockService.calcStockAndPrice(groupId, null, productAttrValues);
            for (StoreProductAttrValue productAttrValue : productAttrValues) {
                StoreCartResponse storeCartResponse = new StoreCartResponse();
                BeanUtils.copyProperties(storeCart,storeCartResponse);

//                StoreProductResponse product = storeProductService.getByProductId(productAttrValue.getProductId(), merId);
//                StoreProduct storeProduct = storeProductService.getById(productAttrValue.getProductId());
                StoreProduct storeProduct = productMap.get(productAttrValue.getProductId());
                StoreProductCartProductInfoResponse p = new StoreProductCartProductInfoResponse();
                BeanUtils.copyProperties(storeProduct,p);
                //批采订单
                BigDecimal levelVipUpPrice = null;
                if(storeCart.getPickingId() > 0){
                    StoreProductPicking productPicking = pickingMap.get(productAttrValue.getSourceSkuId());
                    if(productPicking == null){
                        throw new CrmebException("该批采单商品不存在");
                    }
                    PickingProductResponse productResponse = new PickingProductResponse();
                    BeanUtils.copyProperties(storeProduct,productResponse);
                    productResponse.setCost(productAttrValue.getCost());
                    productResponse.setPrice(productAttrValue.getPrice());
                    productResponse.setWholesalePrice(productPicking.getPrice());
                    productResponse.setPriceType(productPicking.getPriceType());
                    priceUtil.calcPickingProductWholesalePrice(Collections.singletonList(productResponse),channelMerchant.getId(),channelPicking.getReceiptType());
                    productAttrValue.setCost(productResponse.getCost());
                    productAttrValue.setPrice(productResponse.getWholesalePrice());
                    productAttrValue.setTaxAndSecondPrice(productResponse.getTaxAndSecondPrice());
                    storeCartResponse.setPickingProductId(productPicking.getId());
                    storeCartResponse.setIsBtoC(storeCart.getIsBtoC());
                }else {
                    priceUtil.calcProductValuePrice(Collections.singletonList(productAttrValue), channelMerchant.getId(), storeProduct, AreaTypeEnum.CN.getType(), null,false, null,storeCart.getIsBtoC(),null);
                    if(userMemberLevel != null && userMemberLevel.getPriceLadder() == 2){
                        levelVipUpPrice = priceUtil.getLevelVipPrice(channelMerchant, userMemberLevel, productAttrValue.getCost(), productAttrValue.getPrice(), productAttrValue.getTaxAndSecondPrice());
                    }
                    //加价信息
                    p.setPlatRatio(productAttrValue.getPlatRatio());
                    p.setMarkupType(productAttrValue.getMarkupType());
                    p.setPriceChange(productAttrValue.getPriceChange());
                    p.setPriceTailNumber(productAttrValue.getPriceTailNumber());
//                    p.setTaxAndSecondPrice(productAttrValue.getTaxAndSecondPrice());
                }
                if(StringUtils.isBlank(productAttrValue.getImage())){
                    productAttrValue.setImage(storeProduct.getImage());
                }
                if(p.getStockArea()==null){
                    p.setStockArea(StockAreaTempEnum.getByTempId(p.getTempId()).getStockAreaCode());
                }
                p.setSupplierName(storeProduct.getSuppliersName());
                //转换后的价格
                p.setCost(productAttrValue.getCost().setScale(2, RoundingMode.UP));
                p.setPrice(productAttrValue.getPrice().setScale(2, RoundingMode.UP));
                p.setAttrInfo(productAttrValue);
                storeCartResponse.setProductAttrUnique(productAttrValue.getSourceSkuId());
                storeCartResponse.setProductInfo(p);
                // TODO DIDIOK PRICE -7
                storeCartResponse.setTruePrice(productAttrValue.getPrice());
//                storeCartResponse.setPackagePrice(BigDecimal.ZERO);
                storeCartResponse.setTrueStock(productAttrValue.getStock());
                //觅览的成本价
                storeCartResponse.setCostPrice(productAttrValue.getCost().setScale(2, RoundingMode.UP));
                //推送的成本价
                storeCartResponse.setSourceCostPrice(productAttrValue.getSourceCost().setScale(2, RoundingMode.UP));
                storeCartResponse.setPickingId(pickingId);
                storeCartResponse.setReceiptType(channelPicking.getReceiptType());
                storeCartResponse.setTaxAndSecondPrice(productAttrValue.getTaxAndSecondPrice());
                storeCartResponse.setLevelVipUpPrice(levelVipUpPrice);
                storeCartResponse.setMemberLevel(userMemberLevel);
                storeCartResponse.setIsBtoC(storeCart.getIsBtoC());
                storeCartResponse.setRealPlatRatio(productAttrValue.getRealPlatRatio());
                storeCartResponse.setSuppliersRatio(productAttrValue.getSuppliersRatio());
                response.add(storeCartResponse);
            }
        }
        return response;
    }

    /**
     * 根据用户id和购物车id集合获取购物车列表
     * @param userId 当前用户id
     * @param cartIds 购物车id集合
     * @return 购物车列表集合
     */
    @Override
    public List<StoreCart> getList(Integer userId, List<Integer> cartIds) {
        LambdaQueryWrapper<StoreCart> lqwStoreList = new LambdaQueryWrapper<>();
        lqwStoreList.eq(StoreCart::getUid,userId);
        lqwStoreList.eq(StoreCart::getType, "product");
//        lqwStoreList.eq(StoreCart::getI)
        lqwStoreList.in(StoreCart::getId,cartIds);
        lqwStoreList.orderByDesc(StoreCart::getCreateTime);
        return dao.selectList(lqwStoreList);
    }

    /**
     * 购物车数量
     * @param userId Integer 用户id
     * @param type String 类型
     * @param numType boolean 数量类型
     * @author Mr.Zhang
     * @since 2020-05-28
     * @return List<StoreCart>
     */
    @Override
    public Integer getUserCount(Integer userId, String type, boolean numType) {
        if(numType){
            return getUserSumByType(userId, type);
        }else{
            return getUserCountByType(userId, type);
        }
    }

    /**
     * 新增商品至购物车
     * @param storeCart 购物车参数
     * @return 添加后的成功标识
     */
    @Override
    public boolean saveCate(StoreCart storeCart,Integer merId, String jsonStr) {
        String groupId = null;
        if(StringUtils.isNotEmpty(jsonStr)) {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            if(null != jsonObject && null != jsonObject.get("groupId")) {
                groupId = jsonObject.get("groupId").toString();
            }
            if(null != jsonObject && null != jsonObject.get("leaderId")) {
                String leaderId = jsonObject.get("leaderId").toString();
                groupId = getGroupIdByProductIdAndLeaderId(leaderId, storeCart.getProductId(), merId);
            }
        }
        // 判断商品正常
        StoreProductResponse existProduct = storeProductService.getByProductId(storeCart.getProductId(),merId,true,true, groupId, true);

        if(null == existProduct || existProduct.getStock()<=0 || !existProduct.getIsShow()){
            throw new CrmebException("商品已下架");
        }
        List<StoreProductAttrValueResponse> attrList =  existProduct.getAttrValue();
        if(CollectionUtils.isEmpty(attrList)){
            return false;
        }
        // 校验库存是否够用
        boolean stockCheck = false;
        String attrUnique = storeCart.getProductAttrUnique();
        for(StoreProductAttrValueResponse attrValue:attrList){
            if (attrUnique.equalsIgnoreCase(attrValue.getSourceSkuId()) && attrValue.getStock() >= storeCart.getCartNum()) {
                stockCheck = true;
            }
//            if(storeCart.getPickingId() != null){
//                if(attrUnique.equalsIgnoreCase(attrValue.getSourceSkuId())&&attrValue.getStock()>=storeCart.getCartNum()){
//                    stockCheck = true;
//                }
//            }else {
//                if(attrUnique.equalsIgnoreCase(attrValue.getId().toString())&&attrValue.getStock()>=storeCart.getCartNum()){
//                    storeCart.setProductAttrUnique(attrValue.getSourceSkuId());
//                    stockCheck = true;
//                }
//            }
        }
        if(!stockCheck){
            return false;
        }

        // 是否已经有同类型商品在购物车，有则添加数量没有则新增
        StoreCart storeCartPram = new StoreCart();
        storeCartPram.setProductAttrUnique(storeCart.getProductAttrUnique());
        storeCartPram.setUid(userService.getUserId());
        storeCartPram.setIsNew(storeCart.getIsNew());
        if(storeCart.getPickingId() != null){
            storeCartPram.setPickingId(storeCart.getPickingId());
        }
        List<StoreCart> existCarts = getByEntity(storeCartPram); // todo 这里仅仅能获取一条以信息
        if(existCarts.size() > 0){
            StoreCart forUpdateStoreCart = existCarts.get(0);
            // 立即下单的商品，购物车做特殊处理
            if(storeCart.getIsNew()){
                forUpdateStoreCart.setCartNum(storeCart.getCartNum());
            }else{
                forUpdateStoreCart.setCartNum(forUpdateStoreCart.getCartNum()+storeCart.getCartNum());
            }
            //2023.4.7 bug 修改
            forUpdateStoreCart.setIsBtoC(storeCart.getIsBtoC());
            boolean updateResult = updateById(forUpdateStoreCart);
            storeCart.setId(forUpdateStoreCart.getId());

            //记录商品加购数量 author: duyb
            if (updateResult){
                try {
                    saveAddPurchaseNumber(storeCart.getProductId(),merId);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("记录商品加购数量出错!,exception:",e);
                }
            }

            return updateResult;
        }else{
            User currentUser = userService.getInfo();
            storeCart.setUid(currentUser.getUid());
            storeCart.setType("product");
            int insert = dao.insert(storeCart);

            //记录商品加购数量 author: duyb
            if (insert > 0){
                try {
                    saveAddPurchaseNumber(storeCart.getProductId(),merId);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("记录商品加购数量出错!,exception:",e);
                }
            }

            return insert > 0;
        }

    }

    private String getGroupIdByProductIdAndLeaderId(String leaderId, Integer productId ,Integer merId) {
        log.info("getGroupIdByProductIdAndLeaderId 入口：{}，{}，{}" , leaderId, productId, merId);
        if(StringUtils.isEmpty(leaderId) || "0".equals(leaderId) || productId == 0){
            return null;
        }
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);

        //该商户下进行中的拼团活动
        Integer leaderId2;
        try {
            leaderId2 = Integer.valueOf(leaderId);
        }catch (Exception e){
            log.error("数据转换错误 jsonStr:{}", leaderId);
            leaderId2 = 0;
        }
        List<Integer> groupActivityIds = channelGroupBookingService.getInProgressActivityIdsAndLeaderId(channelMerchant.getId(), leaderId2);
        log.info("getGroupIdByProductIdAndLeaderId groupActivityIds：{}，{}" , JSONObject.toJSONString(groupActivityIds));

        //商户下没有进行中的拼团活动，不设置商品拼团价，直接返回
        if (CollectionUtils.isEmpty(groupActivityIds)) {
            return null;
        }
        // 商品sku对应的拼团价格
        StoreProductGroupActivity storeProductGroupActivity = storeProductGroupActivityService.getByIdAndActivityIdList(groupActivityIds, productId);
        log.info("getGroupIdByProductIdAndLeaderId storeProductGroupActivity：{}，{}" , JSONObject.toJSONString(storeProductGroupActivity));

        //没有该商品的活动信息
        if (null == storeProductGroupActivity) {
            return null;
        }else{
            return storeProductGroupActivity.getGroupId();
        }

    }

    /**
     * 记录商品加购数量
     * @author duyb
     * @since 2020-10-12
     */
    @Override
    public void saveAddPurchaseNumber(Integer productId,Integer merId){
        StoreProduct storeProduct = storeProductService.getById(productId);
        StoreProductActive storeProductActive = storeSaleAnalysisService.getOne(Wrappers.<StoreProductActive>lambdaQuery()
                .eq(StoreProductActive::getMerId, merId)
                .eq(StoreProductActive::getProductId, productId)
                .eq(StoreProductActive::getStatisticsDate, DateUtil.nowDateTimeReturnDate("yyyy-MM-dd"))
        );
        if (storeProductActive==null){
            storeProductActive=new StoreProductActive();
            storeProductActive.setMerId(merId);
            storeProductActive.setProductId(productId);
            storeProductActive.setCreateTime(DateUtil.nowDateTime());
            storeProductActive.setStoreName(storeProduct.getStoreName());
            storeProductActive.setAddPurchaseNumber(1);
            storeProductActive.setStatisticsDate(DateUtil.nowDateTimeReturnDate("yyyy-MM-dd"));
        }else {
            storeProductActive.setAddPurchaseNumber(storeProductActive.getAddPurchaseNumber()+1);
        }
        storeSaleAnalysisService.saveOrUpdate(storeProductActive);

    }

    /**
     * 删除购物车信息
     * @param ids 待删除id
     * @return 删除结果状态
     */
    @Override
    public boolean deleteCartByIds(List<Integer> ids) {
        return dao.deleteBatchIds(ids) > 0;
    }

    /**
     * 购物车基本查询
     * @param storeCart 购物车参数
     * @return 购物车结果数据
     */
    @Override
    public List<StoreCart> getByEntity(StoreCart storeCart) {
        LambdaQueryWrapper<StoreCart> lqw = new LambdaQueryWrapper<>();
        lqw.setEntity(storeCart);
        return dao.selectList(lqw);
    }

    /**
     * 检测商品是否有效 更新购物车商品状态
     * @param productId 商品id
     * @return 跟新结果
     */
    @Override
    public boolean productStatusNotEnable(Integer productId) {
//        StoreProductResponse storeProductResponse = storeProductService.getByProductId(productId);
//        if(null == storeProductResponse) return false;
        StoreCart storeCartPram = new StoreCart();
        storeCartPram.setProductId(productId);
        List<StoreCart> existStoreCartProducts = getByEntity(storeCartPram);
        if(null == existStoreCartProducts) return false;
        existStoreCartProducts = existStoreCartProducts.stream().map(e->{
            e.setStatus(false);
            return e;
        }).collect(Collectors.toList());
        return updateBatchById(existStoreCartProducts);
    }

    /**
     * 购物车重选
     * @param resetRequest 重选数据
     * @return 重选结果
     */
    @Override
    public boolean resetCart(CartResetRequest resetRequest) {
        LambdaQueryWrapper<StoreCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StoreCart::getId, resetRequest.getId());
        StoreCart storeCart = dao.selectOne(lqw);
        if(null == storeCart){
            throw new CrmebException("购物车不存在");
        }
        if(null == resetRequest.getNum() || resetRequest.getNum() <= 0 || resetRequest.getNum() >= 999){
            throw new CrmebException("数量不合法");
        }
        storeCart.setCartNum(resetRequest.getNum());
//        StoreProductAttrValue attrValue = storeProductAttrValueService.getById(resetRequest.getUnique());
        storeCart.setProductAttrUnique(resetRequest.getUnique());
        //查看是否已存在相同属性的商品
        StoreCart sameStoreCart = dao.selectOne(Wrappers.lambdaQuery(StoreCart.class)
                .eq(StoreCart::getUid,storeCart.getUid())
                .eq(StoreCart::getType,storeCart.getType())
                .eq(StoreCart::getProductId,storeCart.getProductId())
                .eq(StoreCart::getProductAttrUnique,storeCart.getProductAttrUnique())
                .eq(StoreCart::getIsNew,storeCart.getIsNew())
                .eq(StoreCart::getStatus,true)
                .eq(StoreCart::getPickingId,0)
        );
        if (Objects.nonNull(sameStoreCart)){
            storeCart.setCartNum(storeCart.getCartNum() + sameStoreCart.getCartNum());
            dao.deleteById(sameStoreCart.getId());
        }
        boolean updateResult = dao.updateById(storeCart) > 0;
        if(!updateResult){
            throw new CrmebException("重选添加购物车失败");
        }
        productStatusEnableFlag(resetRequest.getId(), true);
        return updateResult;
    }

    /**
     * 功能描述: 获取购物车勾选的商品所满足的满减送优惠
     * @Param: [storeCartResponses, merId, areaType, notIn]
     * @Return: java.util.List<java.lang.Object>
     * @Author: wangzh
     * @Date: 2023/2/22 9:47
     */
    @Override
    public Object getDiscountGiftProductInfo(List<StoreCartResponse> storeCartResponses, Integer merId, Integer[] areaType, List<Long> unchecked) {
        if (CollectionUtils.isNotEmpty(storeCartResponses)){
            // 剔除未勾选的购物车中的商品
            if (Objects.nonNull(unchecked)){
                storeCartResponses = storeCartResponses.stream().filter(e -> !unchecked.contains(e.getId())).collect(Collectors.toList());
            }
            // 满足的优惠条件
            Map<String, Object> discountInfo = priceUtil.getDiscountPrice(storeCartResponses, merId, areaType[0]);
            return discountInfo.get("giftProductInfos");
        }

        return null;
    }

    ///////////////////////////////////////////////////////////////////自定义方法
    /**
     * 购物车商品种类数量
     * @param userId Integer 用户id
     * @param type String 类型
     * @author Mr.Zhang
     * @since 2020-05-28
     * @return Integer
     */
    private Integer getUserCountByType(Integer userId, String type) {
        //购物车商品种类数量
        LambdaQueryWrapper<StoreCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreCart::getUid, userId)
                .eq(StoreCart::getType, type)
                .eq(StoreCart::getPickingId,0)
                .eq(StoreCart::getIsNew, false);
        return dao.selectCount(lambdaQueryWrapper);
    }

    /**
     * 购物车商品总数量
     * @param userId Integer 用户id
     * @param type String 类型
     * @author Mr.Zhang
     * @since 2020-05-28
     * @return Integer
     */
    private Integer getUserSumByType(Integer userId, String type) {

        Integer cartNum = 0 ;
        LambdaQueryWrapper<StoreCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreCart::getUid, userId);
        queryWrapper.eq(StoreCart::getType,type);
        queryWrapper.eq(StoreCart::getIsNew,false);
        queryWrapper.eq(StoreCart::getStatus, true);
        queryWrapper.eq(StoreCart::getPickingId,0);
        List<StoreCart> carts = dao.selectList(queryWrapper);
        if(null!=carts && carts.size() > 0){
            for(StoreCart cart : carts){
                StoreProduct p =  storeProductService.getById(cart.getProductId());
                if(null != p) {
                    if (p.getStock() > 0 && p.getIsShow()) {
                        cartNum = cart.getCartNum() + cartNum;
                    }
                }
            }
        }
        return cartNum;
    }

    /**
     * 根据购物车id更新状态
     * @param carId 购物车id
     * @param flag 待更新状态值
     * @return 更新结果
     */
    private boolean productStatusEnableFlag(Long carId,boolean flag) {
        StoreCart storeCartPram = new StoreCart();
        storeCartPram.setId(carId);
        List<StoreCart> existStoreCartProducts = getByEntity(storeCartPram);
        if(null == existStoreCartProducts) return false;
        existStoreCartProducts = existStoreCartProducts.stream().map(e->{
            e.setStatus(flag);
            return e;
        }).collect(Collectors.toList());
        return updateBatchById(existStoreCartProducts);
    }

}

